package com.zb.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

// 统计在线人数：看创建了多少个session就有多少人在线
public class OnlineCountListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println(httpSessionEvent.getSession().getId());
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        Object onlineCount = context.getAttribute("OnlineCount");
        if(null == onlineCount){
            onlineCount = 1;
        }else{
            onlineCount = Integer.parseInt(onlineCount.toString()) + 1;
        }
        context.setAttribute("OnlineCount", onlineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        Object onlineCount = context.getAttribute("OnlineCount");
        if(null == onlineCount){
            onlineCount = 0;
        }else{
            onlineCount = Integer.parseInt(onlineCount.toString()) - 1;
        }
        context.setAttribute("OnlineCount", onlineCount);
    }
}
